package com.example.nettydemo.decoder;

import com.alibaba.fastjson.JSON;
import com.example.nettydemo.dto.UserInfo;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.msgpack.MessagePack;

@Slf4j
public class EchoServerHandler extends ChannelHandlerAdapter {

    private int counter;

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 正确的解码方式是???
        UserInfo userInfo= MessagePack.unpack(MessagePack.pack(msg), UserInfo.class);
//        UserInfo userInfo = (UserInfo) msg;
        log.info("request: [{}], counter: [{}]", JSON.toJSONString(userInfo), ++counter);

        ctx.writeAndFlush(userInfo);
    }
}
